package cn.kgc.mybatis;

import cn.kgc.mybatis.entity.User;
import com.mysql.jdbc.Driver;

import java.sql.*;
import java.util.ArrayList;

/**
 * jdbc基本操作
 * 1.导包 mysql-connector-java
 * 2.注册驱动
 * 3.获取连接
 * 4.获取执行sql语句的对象
 * 5.编写sql 发送sql
 * 6.处理结果集
 * 7.释放资源
 *
 * 分析：
 * 1.连接获取的过程繁琐
 * 2.sql语句和java代码存在强耦合关系
 * 3.资源释放过程繁琐     jdbcUtil
 * 4.结果集处理繁琐       commons-dbutils.jar
 * 5.动态sql  ->搜索    字符串的拼接  参数设置   有序集合
 *
 * mybatis 解决   缓存
 *
 */
public class App {
    public static void main( String[] args ) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {


            Driver driver = new Driver();
            DriverManager.registerDriver(driver);
            //  http://www.baidu.com   http 协议
            // jdbc:mysql://   连接数据库的协议
            String url = "jdbc:mysql:///java2218?serverTimezone=UTC&useSSL=false&characterEncoding=UTF-8";
            String username="root";
            String password = "root";

            connection = DriverManager.getConnection(url, username, password);
            System.out.println("connection = " + connection);

            // 查询
            String sql = "select * from user";
            preparedStatement = connection.prepareStatement(sql);
             resultSet = preparedStatement.executeQuery();
            ArrayList<User> users = new ArrayList<>();
            //处理结果集
            while (resultSet.next()){
                int id = resultSet.getInt("id");
                String uname = resultSet.getString(2);
                String pwd = resultSet.getString("password");
                User user = new User();
                user.setId(id);
                user.setUsername(uname);
                user.setPassword(pwd);
                users.add(user);
            }

            System.out.println("users = " + users);

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            //释放资源
            try {
                if( resultSet!=null){
                    resultSet.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }

            try {
                if(preparedStatement!=null){
                    preparedStatement.close();
                }

            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }

            try {
                if(connection!=null){
                    connection.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }

        }

    }
}
